package com.cloud.lan.api;

import com.cloud.lan.entity.base.BaseRequest;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.constant.WxDataConstant;
import com.cloud.lan.service.ILanWxMpService;
import com.cloud.lan.service.tx.wx.config.WxMpConfiguration;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping(value = {"/wx/mp/"})
public class WxMpApi {
    @Resource
    WxMpConfiguration wxMpConfiguration;

    @Resource
    ILanWxMpService lanWxMpService;

    @RequestMapping("qrcode")
    public BaseResponse<Object> getQrcode() {
        String qrcodeUrl = lanWxMpService.getQrcodeUrl("240711");
        return BaseResponse.success(qrcodeUrl);
    }

    @GetMapping("initMenu")
    public String initMenu() throws WxErrorException {
        WxMpService wxMpService = wxMpConfiguration.getMpService(WxDataConstant.MPAPPID);

        WxMenu wxMenu = new WxMenu();

        WxMenuButton button1 = new WxMenuButton();
        button1.setType(WxConsts.MenuButtonType.VIEW);
        button1.setName("兰嘉丝汀");
        button1.setUrl("https://mp.weixin.qq.com/mp/homepage?__biz=Mzk0MzY4ODgyOQ==&hid=1&sn=965f90fab3d895d2545eb5f42f639e90");

        WxMenuButton button2 = new WxMenuButton();
        button2.setName("品牌活动");
        WxMenuButton button2_1 = new WxMenuButton();
        button2_1.setType(WxConsts.MenuButtonType.MINIPROGRAM);
        button2_1.setName("兰嘉丝汀焕肌之旅");
        button2_1.setAppId("wxe5b9fcede6680c3c");
        button2_1.setPagePath("pages/index/index");
        button2_1.setUrl("https://www.lancaster-beauty.com/en");
        button2.getSubButtons().add(button2_1);

        WxMenuButton button3 = new WxMenuButton();
        button3.setName("立即拥有");
//        WxMenuButton button3_1 = new WxMenuButton();
//        button3_1.setType(WxConsts.MenuButtonType.VIEW);
//        button3_1.setName("新加坡新罗免税");
//        button3_1.setUrl("https://www.ishopchangi.com/zh/brand/lancaster");
//        button3.getSubButtons().add(button3_1);

        WxMenuButton button3_1 = new WxMenuButton();
        button3_1.setType(WxConsts.MenuButtonType.MINIPROGRAM);
        button3_1.setName("新加坡新罗免税");
        button3_1.setAppId("wx193e2e5976c4277d");
        button3_1.setPagePath("pages/brandDetail/brandDetail?brandId=lancaster&brandCode=lancaster");
        button3_1.setUrl("https://www.ishopchangi.com/zh/home");
        button3.getSubButtons().add(button3_1);

        WxMenuButton button3_2 = new WxMenuButton();
        button3_2.setType(WxConsts.MenuButtonType.VIEW);
        button3_2.setName("韩国乐天免税");
        button3_2.setUrl("https://chn.lottedfs.cn/kr/display/brand?dispShopNo=10054032");
        button3.getSubButtons().add(button3_2);
        WxMenuButton button3_3 = new WxMenuButton();
        button3_3.setType(WxConsts.MenuButtonType.MINIPROGRAM);
        button3_3.setName("泰国王权免税");
        button3_3.setAppId("wx6bb9e268c2a4f27e");
        button3_3.setPagePath("subPackage/goods/list/index?title=兰嘉丝汀&type=brand&brand=19385");
        button3_3.setUrl("https://www.lancaster-beauty.com/en");
        button3.getSubButtons().add(button3_3);
        // WxMenuButton button3_4 = new WxMenuButton();
        // button3_4.setType(WxConsts.MenuButtonType.MINIPROGRAM);
        // button3_4.setName("中免日上");
        // button3_4.setAppId("wx82028cdb701506f3");
        // button3_4.setPagePath("pages/main/webview/index?url=https%3A%2F%2Fevt.cdfsunrise.com%2Fr%2Fpage%2F%3Fpageid%3D1381f7b2ae000");
        // button3_4.setUrl("https://www.lancaster-beauty.com/en");
        // button3.getSubButtons().add(button3_4);

        wxMenu.getButtons().add(button1);
        wxMenu.getButtons().add(button2);
        wxMenu.getButtons().add(button3);

        wxMpService.getMenuService().menuCreate(wxMenu);

        return "setting success";
    }

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        WxMpService wxMpService = wxMpConfiguration.getMpService(WxDataConstant.MPAPPID);

        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求 timestamp:"+timestamp+";nonce="+nonce+";signature="+signature+";echostr="+echostr;
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String handleWeixinMessage(@RequestBody(required = false) String requestBody,
                                      @RequestParam(name = "signature", required = false) String signature,
                                      @RequestParam(name = "timestamp", required = false) String timestamp,
                                      @RequestParam(name = "nonce", required = false) String nonce,
                                      @RequestParam(name = "openid", required = false) String openid,
                                      @RequestParam(name = "encrypt_type", required = false) String encType,
                                      @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        WxMpService wxMpService = wxMpConfiguration.getMpService(WxDataConstant.MPAPPID);

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        WxMpMessageRouter wxMpMessageRouter = wxMpConfiguration.getRouter(WxDataConstant.MPAPPID);

        log.info("handleWeixinMessage {}, {}, {}, {}, {}, {}, {}", requestBody, signature, timestamp, nonce, openid, encType, msgSignature);
        String out = null;
        if (encType == null) {
            if (requestBody == null) {
                return "";
            }
            // 解析消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            //路由去跳转微信事件
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            //没有微信事件
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            if (requestBody == null) {
                return "";
            }
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }
}
